#import "LCLagMonitor.h"

@implementation LCLagMonitor {
    dispatch_semaphore_t _semaphore;
    CFRunLoopActivity _activity;
    BOOL _isRunning;
}

+ (instancetype)sharedInstance {
    static LCLagMonitor *ins;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ins = [[self alloc] init];
    });
    return ins;
}

- (void)start {
    if (_isRunning) return;
    _isRunning = YES;

    _semaphore = dispatch_semaphore_create(0);

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        while (self->_isRunning) {
            long st = dispatch_semaphore_wait(self->_semaphore, dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC));
            if (st != 0) {
                if (self->_activity == kCFRunLoopBeforeSources || self->_activity == kCFRunLoopAfterWaiting) {
                    NSLog(@"⚠️ [LCLagMonitor] 卡顿检测中...");
                }
            }
        }
    });

    CFRunLoopObserverContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
    CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                                            kCFRunLoopAllActivities,
                                                            YES,
                                                            0,
                                                            &callback,
                                                            &context);
    CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
}

- (void)stop {
    _isRunning = NO;
    dispatch_semaphore_signal(_semaphore);
}

static void callback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    LCLagMonitor *monitor = (__bridge LCLagMonitor *)info;
    monitor->_activity = activity;
    dispatch_semaphore_signal(monitor->_semaphore);
}

@end